"""
表单模板相关的 Pydantic 模型
适配原 Flask 项目的响应格式（驼峰命名）
"""
from pydantic import BaseModel, Field, field_serializer
from typing import Optional, Dict, Any, List
from datetime import datetime


# ========== 模板完整响应（适配原项目） ==========
class TemplateFlaskResponse(BaseModel):
    """
    模板完整响应 - 适配原 Flask 项目的格式
    使用驼峰命名和 _id 字段
    """
    id: int
    name: str
    description: Optional[str] = None
    category: Optional[str] = None
    latest_version: int
    is_active: bool
    created_by: Optional[int] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    version_history: Optional[Any] = None
    
    class Config:
        from_attributes = True
    
    def to_flask_format(self) -> dict:
        """转换为原 Flask 项目的响应格式 
        因为原本mongodb的响应格式是_id, name, version, isActive, createdAt, updatedAt, versionHistory
        但换成了pgsql后，响应格式变成了id, name, version,is_active,  created_at, updated_at, version_history
        为了保证前后端兼容性，需要将pgsql的响应格式转换为mongodb的响应格式
        """
        return {
            "_id": str(self.id),
            "name": self.name,
            "description": self.description,
            "category": self.category,
            "version": self.latest_version,#pgsql的latest_version对应mongodb的version
            "isActive": self.is_active,
            "createdBy": str(self.created_by) if self.created_by else None,
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "updatedAt": self.updated_at.isoformat() if self.updated_at else None,
            "versionHistory": self.version_history
        }


# ========== 模板简要响应（allnames） ==========
class TemplateNameOnly(BaseModel):
    """仅包含 ID 和名称"""
    #字段定义
    id: int
    name: str
    
    #配置：从数据库中获取数据时，自动将数据映射到模型中
    class Config:
        from_attributes = True

    #方法用于将模型数据转换为前端期望的格式：    
    def to_flask_format(self) -> dict:
        return {
            "_id": str(self.id),
            "name": self.name
        }


# ========== 模板名称+版本（allnameswithversion） ==========
class TemplateNameWithVersion(BaseModel):
    """包含 ID、名称和版本"""
    id: int
    name: str
    latest_version: int
    
    class Config:
        from_attributes = True
    
    def to_flask_format(self) -> dict:
        return {
            "_id": str(self.id),
            "name": self.name,
            "version": self.latest_version
        }


# ========== 模板查询响应（query） ==========
class TemplateQueryResponse(BaseModel):
    """查询接口的响应格式"""
    id: int
    name: str
    latest_version: int
    is_active: bool
    version_history: Optional[Any] = None
    created_at: Optional[datetime] = None
    
    class Config:
        from_attributes = True
    
    def to_flask_format(self) -> dict:
        """转换为 query 接口的格式"""
        # 提取版本历史中的版本号
        history_versions = []
        if self.version_history:
            if isinstance(self.version_history, list):
                history_versions = [v.get('version') for v in self.version_history if isinstance(v, dict)]
            elif isinstance(self.version_history, dict):
                history_versions = list(self.version_history.keys())
        
        return {
            "id": str(self.id),
            "name": self.name,
            "currentVersion": self.latest_version,
            "isActive": self.is_active,
            "historyVersions": history_versions,
            "createdAt": self.created_at.isoformat() if self.created_at else None
        }


# ========== 创建/更新模板（保留，以备后用） ==========
class TemplateCreate(BaseModel):
    """创建模板时的输入"""
    name: str
    description: Optional[str] = None
    category: Optional[str] = None
    is_active: bool = True
    created_by: Optional[int] = None
    version_history: Optional[Dict[str, Any]] = None


class TemplateUpdate(BaseModel):
    """更新模板信息"""
    name: Optional[str] = None
    description: Optional[str] = None
    category: Optional[str] = None
    latest_version: Optional[int] = None
    is_active: Optional[bool] = None
    version_history: Optional[Dict[str, Any]] = None

